<?php

/**
 *     52zll.top
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class jssdk {

	function __construct() {
		global $config;

		$this->appid = $config['wx_appid'];
		$this->appsecret = $config['wx_appsecret'];
		$this->debug = 1;
	}


	function getSignPackage() {

		$jsapiTicket = $this->getJsApiTicket();
		$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$timestamp = time();
		$nonceStr = $this->createNonceStr();

		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);

		$signPackage = array(
			"appId"     => $this->appid,
			"nonceStr"  => $nonceStr,
			"timestamp" => $timestamp,
			"url"       => $url,
			"signature" => $signature,
			"rawString" => $string
		);
		return $signPackage; 
	}

	function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}

	function getJsApiTicket() {
		global $_G;

		loadcache('jsapi_ticket');
		$data = $_G['cache']['jsapi_ticket'];
		if ($data['expire_time'] < time()) {
			$accessToken = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
			$res = json_decode($this->httpGet($url));
			$ticket = $res->ticket;
			if ($ticket) {
				$data['expire_time'] = time() + 7000;
				$data['jsapi_ticket'] = $ticket;
				savecache('jsapi_ticket', $data);
			}
		} else {
			$ticket = $data['jsapi_ticket'];
		}

		return $ticket;
	}

	function getAccessToken() {
		global $_G;

		loadcache('access_token');
		$data = $_G['cache']['access_token'];
		if ($data['expire_time'] < time()) {
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
			$res = json_decode($this->httpGet($url));
			$access_token = $res->access_token;
			if ($access_token) {
				$data['expire_time'] = time() + 7000;
				$data['access_token'] = $access_token;
				savecache('access_token', $data);
			}
		} else {
			$access_token = $data['access_token'];
		}

		return $access_token;
	}

	function httpGet($url) {
		if (!function_exists('curl_init')) {
			return '';
		}
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_URL, $url);

		$res = curl_exec($curl);
		curl_close($curl);

		return $res;
	}
}
//From:www_caogen8_co
?>